#include "list.h"

List *init_list(int *nums, int len) // 初始化列表
{
  List *list = (List *)malloc(sizeof(List));
  list->capacity = 10; // 列表默认容量
  list->ratio = 2; // 扩容时容量翻倍
  list->length = len;
  list->arr = (int *)malloc(sizeof(int) * list->capacity);
  for (int i = 0; i < len; i++) list->arr[i] = nums[i];
  return list;
}

int get_length(List *list) // 获取列表长度
{
  return list->length;
}

int get_capacity(List *list) // 获取容量
{
  return list->capacity;
}

void print_list(List *list) // 打印列表
{
  printf("[ ");
  for (int i = 0; i < get_length(list); i++)
  {
    if (i == get_length(list) - 1) printf("%d ", list->arr[i]);
    else printf("%d, ", list->arr[i]);
  }
  puts("]");
}

bool is_full(List *list) // 判断列表是否装满
{
  return get_length(list) == get_capacity(list); 
}

void extend_list(List *list) // 扩容
{
  list->capacity *= list->ratio;
  int *new_arr = (int *)malloc(sizeof(int) * list->capacity);
  int *old_arr = list->arr;
  for (int i = 0; i < list->length; i++) new_arr[i] = old_arr[i];
  list->arr = new_arr;
  free(old_arr);
}

void insert_elem(List *list, int index, int value) // 插入元素
{
  if (is_full(list)) extend_list(list);
  for (int i = list->length - 1; i >= index; i--) list->arr[i + 1] = list->arr[i]; 
  list->arr[index] = value;
  list->length++;
}

void append_elem(List *list, int value) // 追加元素
{
  if (is_full(list)) extend_list(list);
  list->arr[get_length(list)] = value;
  list->length++;
}

int pop_elem(List *list, int index) // 删除元素
{
  int value = list->arr[index];
  for (int i = index; i < get_length(list); i++) list->arr[i] = list->arr[i + 1];
  list->length--;
  return value;
}